package com.tizona;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.lang.reflect.Array;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.tizona.system.Const;
import com.tizona.dao.jdbc.SQLRequest;
import com.tizona.service.*;
import com.tizona.service.impl.*;


/**
 * Resource locator
 */

public class  TarifdConfig
{

    public TarifdConfig(String as[]) throws Exception
    {

        process_active_lc = false;
        debug = 1;
        write_db = true;
        prt_q = false;
        prt_u = false;
        prt_e = false;
        exclude = true;
        collocation = false;
        process_one_lc = -1L;

        tpln = 0l;
        se_mod_id = null;
        lock = true;
                need_read_config = true;
        tarifd_period = 0x493e0;
        tarifd_call_timeout = 10000;
        tz = TimeZone.getDefault();
        loc = Locale.getDefault();
        for(int i = 0; i < Array.getLength(as); i++)
        {
            if(as[i].compareTo("-a") == 0)
                process_active_lc = true;
            if(as[i].compareTo("-w") == 0)
                write_db = true;
            if(as[i].compareTo("-n") == 0)
                debug = 0;
            if(as[i].compareTo("-d") == 0)
                debug = 2;
            if(as[i].compareTo("-q") == 0)
                prt_q = true;
            if(as[i].compareTo("-u") == 0)
                prt_u = true;
            if(as[i].compareTo("-e") == 0)
                prt_e = true;
            if(as[i].compareTo("-f") == 0)
                lock = false;
            if(as[i].compareTo("-x") == 0)
                exclude = false;
            if(as[i].compareTo("-c") == 0)
                collocation = true;
            if(as[i].compareTo("-l") == 0)
            {
                i++;
                process_one_lc = Long.parseLong(as[i]);
                i++;
                lc_period = Integer.parseInt(as[i]);
            }
            if(as[i].compareTo("-t") == 0)
            {
                i++;
                tpln = Long.parseLong(as[i]);
            }
            if(as[i].compareTo("-time") == 0)
            {
                i++;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");

                currentTime = simpleDateFormat.parse(as[i]);
            }
            if(as[i].compareTo("-s") == 0)
            {
                i++;
                se_mod_id = as[i];
                i++;
                se_mod_period = Integer.parseInt(as[i]);
            }
        }

        readConfig();

    }

    public void explain(String s)
    {
        Date date = new Date();
        SimpleDateFormat simpledateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        logger.info(simpledateformat.format(date) + ": " + s);
    }

    public boolean needReadConfig()
    {
        if(need_read_config)
            return true;
        try
        {
            FileInputStream fileinputstream = new FileInputStream(Const.TARIFD_READ_CONFIG_FLAG);
            if(fileinputstream.read() == 49)
                return true;
            fileinputstream.close();
        }
        catch(IOException ioexception)
        {
            logger.error("TARIFD: exception message:" + ioexception.getMessage());
        }
        return false;
    }

    public void readConfig()
        throws Exception
    {

        try
        {
            char ac[] = new char[80];
            FileReader filereader = new FileReader(Const.DBREF_PATH);
            int j = filereader.read(ac, 0, 80);
            filereader.close();
            dbref = new String(ac, 0, j);
        }
        catch(Exception exception)
        {
            logger.error("TARIFD: Cannot read dbref from file " + Const.DBREF_PATH);
            throw exception;
        }
        try
        {
            if(sql != null)
                sql.doClose();
        }
        catch(Exception _ex) { }
        try
        {
            sql = new SQLRequest(dbref);
            ResultSet resultset = sql.query("select VALUE from CONF_STR where NAME='EMAIL_DOMAIN'");
            if(resultset.next())
                email_domain = resultset.getString(1);
            resultset = sql.query("select VALUE from CONF_STR where NAME='EMAIL_FROM'");
            if(resultset.next())
                email_from = resultset.getString(1);
            resultset = sql.query("select VALUE from CONF_STR where NAME='EMAIL_REPLY'");
            if(resultset.next())
                email_reply = resultset.getString(1);
            resultset = sql.query("select VALUE from CONF_INT where NAME='TARIFD_PERIOD'");
            if(resultset.next())
                tarifd_period = resultset.getInt(1) * 1000;
            resultset = sql.query("select VALUE from CONF_INT where NAME='TARIFD_CALL_TIMEOUT'");
            if(resultset.next())
                tarifd_call_timeout = resultset.getInt(1) * 1000;
            
            sql.closeStmtAndRs();
        }
        catch(SQLException exception1) {
//            logger.error(exception1.getNextException().getMessage());
            logger.error("TARIFD: error reading config from database");
            throw exception1;
        }
        need_read_config = false;
        try
        {
            FileOutputStream fileoutputstream = new FileOutputStream(Const.TARIFD_READ_CONFIG_FLAG);
            fileoutputstream.write(48);
            fileoutputstream.close();
        }
        catch(Exception _ex)
        {
            logger.error("Warning: can't write file " + Const.TARIFD_READ_CONFIG_FLAG);
        }

        contractMan = new ContractManagerImpl(this);
        sessionMan = new SessionManagerImpl(this);
        serviceMan = new ServiceManagerImpl(this);
        splitMan = new SplitManagerImpl(this);
        transactionMan = new TransactionManagerImpl(this);
        tarifMan = new TarifManagerImpl(this);

    }

    public boolean process_active_lc;
    public int debug;
    public boolean write_db;
    public boolean prt_q;
    public boolean prt_u;
    public boolean prt_e;
    public boolean exclude;
    public boolean collocation;
    public long tpln;
    public TimeZone tz;
    public Locale loc;
    public int tarifd_period;
    public int tarifd_call_timeout;
    public String email_domain;
    public String email_from;
    public String email_reply;
    public String dbref;
    public SQLRequest sql;
    public long process_one_lc;
    public int lc_period;
    public String se_mod_id;
    public int se_mod_period;
    public boolean lock;
    private boolean need_read_config;

    public Date currentTime;

    //Interfaces for manager
    public ContractManager contractMan;
    public SessionManager sessionMan;
    public ServiceManager serviceMan;
    public SplitManager splitMan;
    public TransactionManager transactionMan;
    public TarifManager tarifMan;

    protected final Log logger = LogFactory.getLog(getClass());

}
